package telebase;

import java.awt.Frame;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

public class ContactsEditView extends javax.swing.JDialog {

    private DB db = new DB();
    ArrayList<WorkObj> wol = new ArrayList<WorkObj>();

    public ContactsEditView(Frame owner, boolean modal) {
        super(owner, modal);
        initComponents();
        i18n();

        jButton3.setEnabled(false);
        jButton4.setEnabled(false);

        WaitingWindow waw = new WaitingWindow();
        RefreshTreeDB();
        RefreshTreeModel();
        waw.close();

        jTree1.setCellRenderer(new ContactsEditViewTreeRenderer());
    }

    private void i18n() {
        setTitle(i18n.get("cev_title"));
        jButton2.setText(i18n.get("cev_b1"));
        jButton3.setText(i18n.get("cev_b2"));
        jButton4.setText(i18n.get("cev_b3"));
        jButton1.setText(i18n.get("cev_b4"));
        //jLabel1.setText(i18n.get("cev_l1"));
        jButton5.setText(i18n.get("cev_editstructure"));
        pack();
    }

    private void RefreshTreeDB() {
        WorkObj wo = null;
        wol.clear();

        ResultSet rs = db.getResultSet("SELECT worknames.k, worknames.workpar, worknames.workname, contacts.k, contacts.contactname " +
                "FROM worknames LEFT JOIN works ON worknames.k = works.workid " +
                "LEFT JOIN contacts ON works.contactid = contacts.k " +
                "ORDER BY worknames.k");
        try {
            while (rs.next()) {
                wo = new WorkObj(rs.getInt("worknames.k"), rs.getInt("worknames.workpar"), rs.getString("worknames.workname"));
                wo.setContname(rs.getString("contacts.contactname"));
                if (rs.getObject("contacts.contactname") == null) {
                    wo.setContid(-1);
                } else {
                    wo.setContid(rs.getInt("contacts.k"));
                }
                wol.add(wo);
            }
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        }
        db.closeResultSet();

        wo = new WorkObj(-1, 0, i18n.get("cev_none"));
        wo.setContid(-1);
        wol.add(wo);

        rs = db.getResultSet("select contacts.k, contacts.contactname from contacts where (select count(*) from works where works.contactid=contacts.k)=0 order by contacts.k");
        try {
            while (rs.next()) {
                wo = new WorkObj(-2, -1, "");
                wo.setContname(rs.getString("contacts.contactname"));
                if (rs.getObject("contacts.contactname") == null) {
                    wo.setContid(-1);
                } else {
                    wo.setContid(rs.getInt("contacts.k"));
                }
                wol.add(wo);
            }
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        }
        db.closeResultSet();
    }

    private void RefreshTreeModel() {
        DefaultMutableTreeNode top = new DefaultMutableTreeNode(i18n.get("kjf_all"));
        RefreshTreeModelReq(0, top);
        DefaultTreeModel tm = new DefaultTreeModel(top);
        jTree1.setModel(tm);
    }

    private void RefreshTreeModelReq(Integer k, DefaultMutableTreeNode node) {
        for (WorkObj w : wol) {
            if (w.getWorkpar().equals(k)) {
                DefaultMutableTreeNode dmtn = new DefaultMutableTreeNode(w);
                node.add(dmtn);
                RefreshTreeModelReq(w.getK(), dmtn);
            }
        }
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTree1 = new javax.swing.JTree();
        jButton5 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(675, 530));
        setModal(true);

        jButton1.setText("Close");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Add");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Edit");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText("Remove");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jTree1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTree1MouseClicked(evt);
            }
        });
        jTree1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTree1KeyReleased(evt);
            }
        });
        jScrollPane2.setViewportView(jTree1);

        jButton5.setText("Edit company structure");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 680, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton4)
                        .addGap(18, 18, 18)
                        .addComponent(jButton5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 265, Short.MAX_VALUE)
                        .addComponent(jButton1)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 463, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2)
                    .addComponent(jButton3)
                    .addComponent(jButton4)
                    .addComponent(jButton5))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        dispose();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        ContactAdd dlg = new ContactAdd(null, true);
        dlg.setVisible(true);
        WaitingWindow waw = new WaitingWindow();
        RefreshTreeDB();
        RefreshTreeModel();
        waw.close();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getLastSelectedPathComponent();
        if (node == null || node.isRoot()) {
            System.out.println("null or root");
            return;
        }

        WorkObj wo = (WorkObj) node.getUserObject();
        ContObj co = new ContObj(wo.getContid());

        ContactEdit dlg = new ContactEdit(null, true, co);
        dlg.setVisible(true);

        WaitingWindow waw = new WaitingWindow();
        RefreshTreeDB();
        RefreshTreeModel();
        waw.close();
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getLastSelectedPathComponent();
        if (node == null || node.isRoot()) {
            System.out.println("null or root");
            return;
        }

        if (JOptionPane.showConfirmDialog(null,
                i18n.get("cont_del_q"),
                i18n.get("cont_del_c"),
                JOptionPane.YES_NO_OPTION) ==
                JOptionPane.YES_OPTION) {
            WorkObj wo = (WorkObj) node.getUserObject();

            db.executeNonQuery("delete from contacts where k=" + wo.getContid());
            db.executeNonQuery("delete from phones where contactid=" + wo.getContid());
            db.executeNonQuery("delete from works where contactid=" + wo.getContid());

            WaitingWindow waw = new WaitingWindow();
            RefreshTreeDB();
            RefreshTreeModel();
            waw.close();
        }
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        CompanyJobsFrame frm = new CompanyJobsFrame(null, true, false);
        frm.setLocationRelativeTo(null);
        frm.setVisible(true);
        WaitingWindow waw = new WaitingWindow();
        RefreshTreeDB();
        RefreshTreeModel();
        waw.close();
    }//GEN-LAST:event_jButton5ActionPerformed

    private void jTree1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTree1MouseClicked
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getLastSelectedPathComponent();

        if (node == null || node.isRoot()) {
            return;
        }

        WorkObj wo = (WorkObj) node.getUserObject();
        if (wo.getContid().equals(-1)) {
            jButton3.setEnabled(false);
            jButton4.setEnabled(false);
        } else {
            jButton3.setEnabled(true);
            jButton4.setEnabled(true);
        }
    }//GEN-LAST:event_jTree1MouseClicked

    private void jTree1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTree1KeyReleased
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getLastSelectedPathComponent();

        if (node == null || node.isRoot()) {
            return;
        }

        WorkObj wo = (WorkObj) node.getUserObject();
        if (wo.getContid().equals(-1)) {
            jButton3.setEnabled(false);
            jButton4.setEnabled(false);
        } else {
            jButton3.setEnabled(true);
            jButton4.setEnabled(true);
        }
    }//GEN-LAST:event_jTree1KeyReleased

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTree jTree1;
    // End of variables declaration//GEN-END:variables
}
